package com.harmony.pilot.completion.client;

import com.harmony.pilot.common.dto.FunctionImplementation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.HashMap;
import java.util.Map;

/**
 * 函数实现查询客户端
 * 用于获取函数实现，增强代码补全提示
 */
@Slf4j
@Component
public class FunctionImplementationClient {
    
    private final WebClient webClient;
    
    public FunctionImplementationClient(@Value("${service.data.url}") String dataServiceUrl) {
        this.webClient = WebClient.builder()
                .baseUrl(dataServiceUrl)
                .build();
    }
    
    /**
     * 查找函数实现
     */
    public FunctionImplementation findFunctionImplementation(
            String functionName, 
            String qualifiedName,
            String contextFilePath) {
        
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("functionName", functionName);
            if (qualifiedName != null) {
                request.put("qualifiedName", qualifiedName);
            }
            if (contextFilePath != null) {
                request.put("contextFilePath", contextFilePath);
            }
            
            return webClient.post()
                    .uri("/data/function/implementation")
                    .bodyValue(request)
                    .retrieve()
                    .bodyToMono(FunctionImplementation.class)
                    .block();
                    
        } catch (Exception e) {
            log.error("Failed to find function implementation", e);
            return null;
        }
    }
    
    /**
     * 从代码上下文查找函数实现
     */
    public FunctionImplementation findFunctionImplementationFromContext(
            String filePath,
            String code,
            int cursorLine,
            int cursorColumn) {
        
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("filePath", filePath);
            request.put("code", code);
            request.put("cursorLine", cursorLine);
            request.put("cursorColumn", cursorColumn);
            
            return webClient.post()
                    .uri("/data/function/implementation/from-context")
                    .bodyValue(request)
                    .retrieve()
                    .bodyToMono(FunctionImplementation.class)
                    .block();
                    
        } catch (Exception e) {
            log.error("Failed to find function implementation from context", e);
            return null;
        }
    }
}

